#include "battery_bsp.h"

uint16_t batteryGetVolt(void)
{
    /* enable ADC clock */
    rcu_periph_clock_enable(RCU_ADC);
    /* config ADC clock */
    rcu_adc_clock_config(RCU_ADCCK_APB2_DIV2);

    /* ADC data alignment config */
    adc_data_alignment_config(ADC_DATAALIGN_RIGHT);
    /* ADC channel length config */
    adc_channel_length_config(ADC_ROUTINE_CHANNEL, 1U);

    /* ADC trigger config */
    adc_external_trigger_source_config(ADC_ROUTINE_CHANNEL, ADC_EXTTRIG_ROUTINE_NONE);
    /* ADC external trigger config */
    adc_external_trigger_config(ADC_ROUTINE_CHANNEL, ENABLE);

    /* ADC Vrefint enable */
    adc_channel_16_to_19(ADC_INTERNAL_CHANNEL_SWITCH, ENABLE);
    adc_channel_16_to_19(ADC_VBAT_CHANNEL_SWITCH, ENABLE);

    /* enable ADC interface */
    adc_enable();
    delay_1ms(1U);
    /* ADC calibration and reset calibration */
    adc_calibration_enable();

    /* ADC internal reference voltage channel config */
    adc_routine_channel_config(0U, ADC_CHANNEL_17, ADC_SAMPLETIME_239POINT5);
    /* ADC software trigger enable */
    adc_software_trigger_enable(ADC_ROUTINE_CHANNEL);
    /* wait the end of conversion flag */
    while (!adc_flag_get(ADC_FLAG_EOC))
        ;
    /* clear the end of conversion flag */
    adc_flag_clear(ADC_FLAG_EOC);
    /* return routine channel sample value */

    uint16_t volt = adc_routine_data_read();

    /* ADC software trigger enable */
    adc_routine_channel_config(0U, ADC_CHANNEL_18, ADC_SAMPLETIME_239POINT5);
    adc_software_trigger_enable(ADC_ROUTINE_CHANNEL);
    /* wait the end of conversion flag */
    while (!adc_flag_get(ADC_FLAG_EOC))
        ;
    /* clear the end of conversion flag */
    adc_flag_clear(ADC_FLAG_EOC);
    /* return routine channel sample value */

    volt = 3600 * adc_routine_data_read() / volt;
    adc_disable();

    rcu_periph_clock_disable(RCU_ADC);

    return volt;
}

uint8_t batteryIsLow(void)
{
	uint16_t volt = batteryGetVolt();
    if (volt < BATTERY_LOW_LEVEL)
    {
        return 1;
    }
    else
    {
        return 0;
    }
}